const coupon = require('../../templates/coupon/coupon');

Page({
  data: {
    pageIndex: 1,
    list: [],
    loading: false,
    noMore: false,
  },
  onLoad: function(options) {
    this.getCoupons();
  },
  onPullDownRefresh: function() {
    this.setData({
      list: [],
      loading: true,
      noMore: false
    }, () => {
      this.getCoupons();
      wx.stopPullDownRefresh();
    });
  },
  onReachBottom: function() {
    if (this.data.noMore) return;
    this.setData({
      loading: true
    });
    this.getCoupons();
  },
  getCoupons: function () {
    wx.util.request('marketing.coupon.list').then(res => {
      let news = coupon.format(res);
      this.setData({
        list: this.data.list.concat(news),
        pageIndex: this.data.pageIndex + 1,
        noMore: res.length < 10
      });
    }).catch(err => {
      console.log(err);
    });
  },
  receive: function (e) {
    coupon.receive(e.currentTarget.dataset.id);
  }
})